package com.news.service;

import com.news.config.Constant;
import com.news.dao.ImageDao;
import com.news.exception.BusinessError;
import com.news.exception.BusinessException;
import com.news.model.ImageEntity;
import com.news.util.ImageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by 凌志远.
 * Create Date : 2015/7/28.
 * Create TIME : 18:04.
 * Discription:
 * <p>
 * 图片业务逻辑处理类-ImageService
 */

@Service(value = "imageService")
@Transactional
public class ImageService {

    @Resource
    private ImageDao imageDao;

    public ImageEntity uploadImage(MultipartFile imageFile) {

        String name = null;
        String thumb = null;
        String url = null;
        long size = 0l;
        long now = new Date().getTime();

        ImageEntity image = new ImageEntity();

        if (imageFile == null || imageFile.isEmpty()) {
            throw new BusinessException(BusinessError.ERROR_INVALID_IMAGE);
        }

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        //验证图片格式
        String contentType = imageFile.getContentType();
        //取得文件类型
        String type = null;
        String real_type = null;
        if (contentType.equalsIgnoreCase("image/jpeg")
                || contentType.equalsIgnoreCase("image/pjpeg")
                || contentType.equalsIgnoreCase("image/jpg")) {
            type = ".jpg";
            real_type = "image/jpeg";
        }
        if (contentType.equalsIgnoreCase("image/png")) {
            real_type = "image/png";
            type = ".png";
        }

        name = uuid + type;
        size = imageFile.getSize();
        try {

            url = ImageUtil.saveImageFile(imageFile, uuid);
            thumb = ImageUtil.saveThumnailImage(imageFile.getInputStream(), Constant.IMAGE_THUMBNAIL_WIDTH, Constant.IMAGE_THUMBNAIL_HEIGHT, uuid);
        } catch (Exception ex) {
            throw new BusinessException(BusinessError.ERROR_INVALID_IMAGE_TYPE);
        }

        image.setName(name);
        image.setThumb(thumb);
        image.setUrl(url);
        image.setSize(size);
        image.setType(real_type);
        image.setCreate_time(now);

        imageDao.saveOrUpdate(image);

        return image;
    }

    public Map listImages(int page_size, int page_num) {

        Map result = new HashMap<>();
        result.put("images", imageDao.listImages(page_size, page_num));
        result.put("totalRows", imageDao.count(ImageEntity.class));
        return result;

    }
}
